package com.xudongbase.common.fastjson.serializer;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * fastjson自定义日期时间序列化类
 *
 * @author xudongmaster
 */
@Component("fastjsonCustomDateTimeSerializer")
public class CustomDateTimeSerializer implements ObjectSerializer {
    /**
     * 日期时间格式
     */
    @Value("${json.dateTime.format}")
    private String format;

    /**
     * 序列化方法（重写）
     *
     * @param serializer 序列化类
     * @param object     对象
     * @param fieldName  字段名称
     * @param fieldType  字段类型
     * @param features   特性
     */
    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) {
        SerializeWriter out = serializer.getWriter();
        if (object == null) {
            out.writeNull();
            return;
        }
        //指定日期格式
        if (object instanceof Date) {
            out.writeString(DateUtil.format((Date) object, format));
        } else if (object instanceof LocalDateTime) {
            out.writeString(((LocalDateTime) object).format(DateTimeFormatter.ofPattern(format)));
        }
    }

}